package com.smartphone.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;

import com.smartphone.MainActivity;
import com.smartphone.MainApplication;
import com.smartphone.R;
import com.smartphone.core.Smartphone;
import com.smartphone.core.SmartphoneState;

import java.util.Timer;
import java.util.TimerTask;

public class SmartphoneService extends Service {
    private static final String TAG = "SmartphoneService";
    private Smartphone sp = Smartphone.getInstance();
    private final Handler mIterateHandler = new Handler();
    private Timer registerTimer = new Timer();
    private TimerTask registerTimerTask;
    private SharedPreferences shared;
    private SharedPreferences.Editor editor;
    private NotificationManager manager;
    private Notification notification;
    private RemoteViews remoteViews;
    private RegistrationReceiver mRegistrationReceiver;
    public SmartphoneService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MainApplication app = (MainApplication) getApplication();
        shared = app.getMyprefs();
        editor = shared.edit();
        createNotification(this);

        mIterateHandler.post(new Runnable() {
            @Override
            public void run() {
                sp.iterate();
                mIterateHandler.postDelayed(this, 20);
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(sp.BroadcastRegistration);
        mRegistrationReceiver = new RegistrationReceiver();
        registerReceiver(mRegistrationReceiver, filter);


        if(app.getSettingsPrefs().getBoolean("auto_register",false)) {
            String username = shared.getString("edtUsername", null);
            String password = shared.getString("edtPassword", null);
            String server = shared.getString("edtServer", null);
            int type = shared.getInt("ratioTransport", 0);
            String dispname = app.getSettingsPrefs().getString("dispname", null);
            sp.register(server, type,
                    dispname, username, password, 3600);
        }
        String dispname = app.getSettingsPrefs().getString("dispname", null);
        String username = app.getSettingsPrefs().getString("username", null);
        sp.setPrimaryContact(dispname, username);

        boolean echo_cancellation = app.getSettingsPrefs().getBoolean("echo_cancellation", false);
        sp.enableEchoCancellation(echo_cancellation);
        boolean adaptive_rate = app.getSettingsPrefs().getBoolean("adaptive_rate", false);
        sp.enableAdaptiveRrateControl(adaptive_rate);

        String strPort = app.getSettingsPrefs().getString("port", "5060");
        sp.setLocalPort(Integer.valueOf(strPort));

        registerTimerTask = new TimerTask() {
            @Override
            public void run() {
                sp.refreshRegisters();
            }
        };
        registerTimer.schedule(registerTimerTask, 0, 60000);

        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        registerTimer.cancel();
    }

    private void createNotification(Service service) {
        Intent intentMain = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intentMain, 0);
        remoteViews = new RemoteViews(getPackageName(), R.layout.remoteviews);

        remoteViews.setImageViewResource(R.id.iv_head, R.mipmap.ic_launcher);


        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        notification = builder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCustomContentView(remoteViews)
                .setContentIntent(pIntent)
                .build();
        notification.flags =   Notification.FLAG_FOREGROUND_SERVICE;

        service.startForeground(1, notification);
    }
    class RegistrationReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int state = (int) bundle.get("state");
            String message = (String) bundle.get("message");
            switch (state) {
                case SmartphoneState.RegistrationNone:
                    remoteViews.setTextViewText(R.id.tv_content, getResources().getString(R.string.register_none));
                    SmartphoneService.this.startForeground(1, notification);
                    break;
                case SmartphoneState.RegistrationProgress:
                    remoteViews.setTextViewText(R.id.tv_content, getResources().getString(R.string.register_progress));
                    SmartphoneService.this.startForeground(1, notification);
                    break;
                case SmartphoneState.RegistrationOk:
                    remoteViews.setTextViewText(R.id.tv_content, getResources().getString(R.string.register_ok));
                    SmartphoneService.this.startForeground(1, notification);
                    break;
                case SmartphoneState.RegistrationCleared:
                    remoteViews.setTextViewText(R.id.tv_content, getResources().getString(R.string.register_cleared));
                    SmartphoneService.this.startForeground(1, notification);
                    break;
                case SmartphoneState.RegistrationFailed:
                    remoteViews.setTextViewText(R.id.tv_content, getResources().getString(R.string.register_fail)
                            + " : " + message);
                    SmartphoneService.this.startForeground(1, notification);
                    break;
                default:
                    break;
            }
        }
    }

}
